package com.javajun.douban;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javajun.douban.entity.YumImage;

public class ImageUtil {
    
    public YumImage uploadImg(String img) {
        if (img == null) {
            img = "";
        }
        YumImage result = new YumImage();
        String json = "";
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            String urlString = "https://api.yum6.cn/sinaimg.php?img=" + img;
            URL httpUrl = new URL(urlString);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Charset", "UTF-8");
            // conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("User-Agent", 
                    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:63.0) Gecko/20100101 Firefox/63.0");
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 状态码
            Integer statusCode = conn.getResponseCode();
            
            // 设置连接主机超时（单位：毫秒）
            conn.setConnectTimeout(3 * 10000);
            // 设置从主机读取数据超时（单位：毫秒）
            conn.setReadTimeout(3 * 10000);
            if (statusCode == HttpURLConnection.HTTP_OK) {
                
                // 建立实际的连接
                conn.connect();
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line = null;
                StringBuffer strBuffer = new StringBuffer();
                while ((line = in.readLine()) != null) {
                    // bookJson += line;
                    strBuffer.append(line);
                }
                json = strBuffer.toString();
                System.out.println("这是一个数据：" + json);
                ObjectMapper mapper = new ObjectMapper();
                result = mapper.readValue(json, YumImage.class);
                
            } else {
                json = "\"msg\":\"book_not_found\",\"code\":6000,\"request\":\"GET \\/v2\\/book\\/isbn\\/:"+img+"\"";
                
            }
                
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
         // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
                conn.disconnect();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}
